package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.exception.BizException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    // 注入菜品和套餐的mapper
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void removeCategoryById(Long id) {
//        // 做判断
//        int count = 10 ;
//        if (count>0){
//            // 说明有菜品,要提醒用户
//            return R.error("已有菜品,无法删除");
//        }


        // 删除分类之前
        // 先检查有没有菜品
        // selete count(*) from dish where category_id = ?
        Integer count1 = dishMapper.selectCount(new LambdaQueryWrapper<Dish>()
                .eq(Dish::getCategoryId, id));
        if (count1>0){
            // 要抛异常
            throw new BizException("该分类下已有菜品,无法删除 请先去删除该分类下的菜品.");
        }
        // 再检查有没有套餐
        // selete count(*) from set_meal where category_id = ?
        Integer count2 = setmealMapper.selectCount(new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getCategoryId,id));
        if (count2>0){
            // 要抛异常
            throw new BizException("该分类下已有套餐,无法删除 请先去删除该分类下的套餐.");
        }
        // 都没有 可以直接删除
        // this  CategoryService提供的方法
        this.removeById(id);
    }
}
